package com.vast.admin.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.entity.Arbitration;
import com.vast.admin.entity.ArbitrationFlow;
import com.vast.admin.entity.ArbitrationFlowChangeRecord;
import com.vast.admin.entity.enums.OperatorEum;
import com.vast.admin.entity.enums.QueryOrderEnum;
import com.vast.admin.mapper.ArbitrationMapper;
import com.vast.admin.utils.QueryBuilder;
import com.vast.admin.utils.TableFieldColumnsUtils;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.common.utils.StringUtils;
import com.vast.system.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class ArbitrationService extends ServiceImpl<ArbitrationMapper, Arbitration> {


    @Autowired
    private ArbitrationFlowService arbitrationFlowService;

    @Autowired
    private ArbitrationFlowChangeRecordService flowChangeRecordService;

    public IPage<Arbitration> queryList(SysUser manager, Page<Arbitration> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
        QueryWrapper<Arbitration> queryWrapper = new QueryWrapper<>();
        Map<String, String> fieldColumns = TableFieldColumnsUtils.getInstance().getFieldTableColumns(Arbitration.class);
        if (listMode) {
            // size 小于 0 不在查询 total 及分页，自动调整为列表模式。
            // 注意！！这个地方自己控制好！！
            page.setSize(-1);
        }
        if (!StringUtils.isEmpty(queryItems)) {
            List<QueryBuilder> queryBuilders = new ArrayList<>();
            String[] queryItemArr = queryItems.split(";");
            if (queryItemArr.length > 0) {
                for (String queryItemStr : queryItemArr) {
                    String[] itemArr = queryItemStr.split(",");
                    if (itemArr.length == 3) {
                        String as = itemArr[1];
                        String params = itemArr[2];
                        if (!StringUtils.isEmpty(params)) {
                            queryBuilders.add(new QueryBuilder(itemArr[0], OperatorEum.valueOf(as), itemArr[2]));
                        }
                    }
                }
            }

            for (QueryBuilder queryBuilder : queryBuilders) {
                //查询字段
                String field = queryBuilder.getField();
                //查询参数值
                String params = queryBuilder.getParams();
                if (fieldColumns.containsKey(field) && !StringUtils.isEmpty(params)) {
                    //表属性
                    String tableColumn = fieldColumns.get(field);
                    if (queryBuilder.getAs() == OperatorEum.EQ) {
                        queryWrapper.eq(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LIKE) {
                        queryWrapper.like(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LIKELEFT) {
                        queryWrapper.likeLeft(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LIKERIGHT) {
                        queryWrapper.likeRight(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.GE) {
                        queryWrapper.ge(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LE) {
                        queryWrapper.le(tableColumn, params);
                    }
                }
            }
        }

        if (!manager.isHasRole(Constant.SUPER_ADMIN)) {//超级管理员
            queryWrapper.eq(Arbitration.COL_COMPANY_ID, manager.getCompanyId());
        }

        if (!StringUtils.isEmpty(orderField)) {
            String[] orderByColumns = orderField.split(",");
            String queryOrderByColumns = "";
            if (orderByColumns.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (String orderByColumn : orderByColumns) {
                    if (fieldColumns.containsKey(orderByColumn)) {
                        sb.append(fieldColumns.get(orderByColumn)).append(",");
                    }
                }
                if (sb.length() > 0) {
                    queryOrderByColumns = sb.deleteCharAt(sb.length() - 1).toString();
                }
            }
            if (!StringUtils.isEmpty(queryOrderByColumns)) {
                if (order == null) {
                    order = QueryOrderEnum.ASC;
                }
                if (order == QueryOrderEnum.ASC) {
                    queryWrapper.orderByAsc(queryOrderByColumns);
                } else if (order == QueryOrderEnum.DESC) {
                    queryWrapper.orderByDesc(queryOrderByColumns);
                }
            }

        }

        IPage<Arbitration> result = baseMapper.selectPage(page, queryWrapper);
        for (Arbitration record : result.getRecords()) {
            if (record.getArbitrationFlowId() > 0) {
                //诉讼流程类型
                ArbitrationFlow ArbitrationFlow = arbitrationFlowService.getById(record.getArbitrationFlowId());
                if (ArbitrationFlow != null) {
                    record.setArbitrationFlowName(ArbitrationFlow.getName());
                }
                //当前诉讼流程节点类型
                ArbitrationFlow ArbitrationFlowType = arbitrationFlowService.getById(record.getArbitrationFlowTypeId());
                if (ArbitrationFlowType != null) {
                    record.setArbitrationFlowTypeName(ArbitrationFlowType.getName());
                }
            }
        }

        return result;
    }

    public boolean addOrUpdate(SysUser manager, Arbitration bean) {
        if (bean.getId() == null) {
            bean.setCompanyId(manager.getCompanyId());
            bean.setCreateBy(manager.getUserId());
            bean.setUpdateBy(manager.getUserId());
            bean.setCreateTime(DateTime.now());
            bean.setUpdateTime(DateTime.now());
            bean.setValid(1);

            //流程变更记录
            ArbitrationFlowChangeRecord flowChangeRecord = new ArbitrationFlowChangeRecord();

            ArbitrationFlow ArbitrationFlow = arbitrationFlowService.getById(bean.getArbitrationFlowId());
            if (ArbitrationFlow != null) {
                List<ArbitrationFlow> ArbitrationFlows = arbitrationFlowService.list(new QueryWrapper<ArbitrationFlow>().eq(ArbitrationFlow.COL_PARENT_ID, ArbitrationFlow.getId()).orderByAsc(ArbitrationFlow.COL_SORT));
                if (ArbitrationFlows != null && !ArbitrationFlows.isEmpty()) {
                    ArbitrationFlow flow = ArbitrationFlows.get(0); //创建诉讼后默认流程步骤为第一条
                    bean.setArbitrationFlowTypeId(flow.getId()); //设置当前诉讼流程类型id;
                    bean.setStatus(flow.getSort()); //设置默认完成创建步骤

                    flowChangeRecord.setArbitrationFlowId(flow.getId());
                    flowChangeRecord.setArbitrationFlowNodeName(flow.getName());
                    flowChangeRecord.setStatus(flow.getSort());

                }
            }
            //添加
            baseMapper.insert(bean);

            flowChangeRecord.setArbitrationId(bean.getId());
            flowChangeRecord.setRemark(bean.getRemark());
            flowChangeRecord.setCreateBy(manager.getUserId());
            flowChangeRecord.setUpdateBy(manager.getUserId());
            flowChangeRecord.setValid(1);
            flowChangeRecord.setCreateTime(DateTime.now());
            flowChangeRecord.setUpdateTime(DateTime.now());
            flowChangeRecordService.save(flowChangeRecord);

            return true;
        } else {
            bean.setUpdateBy(manager.getUserId());
            bean.setUpdateTime(DateTime.now());
            bean.setValid(1);
            baseMapper.updateById(bean);
//
            return true;
//            return roleMenuService.saveBatch(roleMenus);
        }
    }

    public Arbitration info(SysUser manager, Long id) {
        Arbitration bean = baseMapper.selectById(id);
        if (bean.getArbitrationFlowId() > 0) {
            ArbitrationFlow ArbitrationFlow = arbitrationFlowService.getById(bean.getArbitrationFlowId());
            if (ArbitrationFlow != null) {
                bean.setArbitrationFlowName(ArbitrationFlow.getName());
            }
        }
        return bean;
    }


    public boolean delete(SysUser manager, Long[] ids) {

        List<Long> idsList = Arrays.asList(ids);
        int count = baseMapper.deleteBatchIds(idsList);

        return count == ids.length;

    }

//    public IPage<Arbitration> getArbitrationDueByDays(Page<Arbitration> page, int days) {
//        IPage<Arbitration> result = baseMapper.getArbitrationDueByDays(page, days);
//        for (Arbitration record : result.getRecords()) {
//            if (record.getArbitrationFlowId() > 0) {
//                //流程类型
//                ArbitrationFlow ArbitrationFlow = arbitrationFlowService.getById(record.getArbitrationFlowId());
//                if (ArbitrationFlow != null) {
//                    record.setArbitrationFlowName(ArbitrationFlow.getName());
//                }
//                //当前诉讼流程节点类型
//                ArbitrationFlow ArbitrationFlowType = arbitrationFlowService.getById(record.getArbitrationFlowTypeId());
//                if (ArbitrationFlowType != null) {
//                    record.setArbitrationFlowTypeName(ArbitrationFlowType.getName());
//                }
//            }
//        }
//        return result;
//    }

}


